<?php

namespace Service\Http\Controller;

use Service\AjaxModel\AjaxResponse;
use Service\Http\Exception\RestException;
use Service\Http\Request;
use Service\Model\User;
use Service\Providers\TokenAuthenticateProviders;

class AuthController extends Controller
{

    /**
     * @throws RestException
     */
    public function available(Request $request): AjaxResponse
    {
        $user = new User();
        $result = $user->select([['email', '=', $request->queryString['email']]]);
        return AjaxResponse::success(['available' => $result->num_rows === 0]);
    }

    /**
     * @throws RestException
     */
    public function register(Request $request): AjaxResponse
    {
        $user = new User();
        $user->id = md5(rand());
        $user->email = $request->payload['email'];
        $user->username = $request->payload['username'];
        $user->password = $request->payload['password'];
        $user->admin = 0;
        try {
            $result = $user->insert();
        } catch (RestException $e) {
            throw new RestException('用户名已存在', 400);
        }
        return AjaxResponse::success(['success' => $result]);
    }

    /**
     * @throws RestException
     */
    public function token(Request $request): AjaxResponse
    {
        $user = new User();
        $result = $user->select([['email', '=', $request->payload['email']], ['password', '=', $request->payload['password']]]);
        if ($result->num_rows === 0) {
            throw new RestException("用户登录失败", 400);
        }
        $user->password = '';
        $token = TokenAuthenticateProviders::createToken($user);
        return AjaxResponse::success(['token' => $token]);
    }

}
